package com.ctyon.watchmanager.viewmodel;

import android.app.Application;


import com.ctyon.common.util.SPUtils;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.DataRepository;
import com.ctyon.watchmanager.model.db.entity.LoginHistoryEntity;
import com.ctyon.watchmanager.model.net.entity.Manager;

import java.util.Date;
import java.util.List;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;

import static com.ctyon.watchmanager.config.OssConfig.endpoint;
import static com.ctyon.watchmanager.config.OssConfig.picture;

/**
 * CreateDate：19-1-11 on 下午4:39
 * Describe:
 * Coder: lee
 */
public class LoginViewModel extends AndroidViewModel {

    private final DataRepository mRepository;
    private final MediatorLiveData<List<LoginHistoryEntity>> mObservableHistories;

    public LoginViewModel(Application application) {
        super(application);

        mObservableHistories = new MediatorLiveData<>();

        mObservableHistories.setValue(null);

        mRepository = ((BasicApp) application).getRepository();

        LiveData<List<LoginHistoryEntity>> loginHistories = mRepository.loadLoginHistory();

        // observe the changes of the products from the database and forward them
        mObservableHistories.addSource(loginHistories, mObservableHistories::setValue);
    }

    public MediatorLiveData<List<LoginHistoryEntity>> getmObservableHistories() {
        return mObservableHistories;
    }

    public void insertHistory(Manager manager){
        BasicApp.getInstance().getAppExecutors().diskIO().execute(() -> {
            LoginHistoryEntity historyEntity = new LoginHistoryEntity();
            historyEntity.setUserId(manager.getManagerId());
            historyEntity.setUserName(manager.getNickName());
            historyEntity.setPassword(manager.getPassword());
            historyEntity.setUserImgUrl(manager.getImg());
            historyEntity.setLoginDate(new Date());
            mRepository.insertHistory(historyEntity);
        });
    }

}
